import logging


def get_logger(file=None, name="py50", level='INFO',
               ):
    """获取日志收集器"""
    logger = logging.getLogger(name)
    # 这支笔只记录 info 以上等级的信息。
    logger.setLevel(level)

    # 初始化日记本 Handler 处理器
    handler = logging.StreamHandler()
    handler.setLevel(level)

    # 处理器和收集器绑定在一起
    logger.addHandler(handler)

    console_fmt = logging.Formatter(
        fmt="%(name)s】%(levelname)s】%(filename)s】%(lineno)d】%(asctime)s】%(message)s】",
        # fmt1="{asctime}:{name}:{levelname}:{filename}:{lineno}:{message}",
        # datefmt="%Y/%m/%d %H:%M:%S"
    )

    handler.setFormatter(console_fmt)

    # 添加日志文件的处理
    if file is not None:
        file_handler = logging.FileHandler(file, encoding='utf-8')
        file_handler.setLevel(level)
        logger.addHandler(file_handler)
        file_handler.setFormatter(console_fmt)

    return logger


if __name__ == '__main__':
    logger = get_logger(file="py51.log")

    # logger 是日志收集器
    logger.info("这是info")
    logger.info("这是warning")
